<template lang="pug">
.view.cp-manage-role.fix-flex-pos
  .role-staff-wrap
    .role-wrap
      p.wrap-title
        span 角色
        span.title-add(@click="showDialog=true") 添加
      el-table(
      :data="roleList",
      highlight-current-row
      size="mini"
      :row-class-name="tableRowClassName"
      @row-click="clickRoleRow"
      v-loading="loadingRoles")
        el-table-column(align="center", show-overflow-tooltip, type="index", label="序号", :fixed="true")
        el-table-column(align="center", show-overflow-tooltip, prop="roleName", label="角色")
        el-table-column(align="center", show-overflow-tooltip, prop="roleType", label="类型")
          template(slot-scope="scope")
            span(v-text="scope.row.roleType ? '系统角色' : '自定义角色'")
        el-table-column(align="center", label="操作", min-width="48px")
          template(slot-scope="scope", v-if="scope.row.roleType !== 'system'")
            el-tooltip(content="删除")
              i.icon-act.el-icon-delete(@click="deleteRole($event, scope.row, scope.$index)")
      p.wrap-title(style="margin-bottom: 6px; margin-top: 16px")
        span 员工
        el-input.title-search(v-model="employeeId", placeholder="员工号，按回车键", size="mini", suffix-icon="el-icon-search", @keyup.enter.native="searchRoleEmployee")
        span.title-add(@click="addStaffForRole") 添加
      el-table(
      :data="staffList",
      highlight-current-row
      size="mini"
      v-loading="loadingStaffs")
        el-table-column(align="center", show-overflow-tooltip, type="index", label="序号", :fixed="true")
        el-table-column(align="center", show-overflow-tooltip, prop="name", label="员工姓名")
        el-table-column(align="center", show-overflow-tooltip, prop="employeeId", label="员工号")
        el-table-column(align="center", label="操作", min-width="48px")
          template(slot-scope="scope")
            el-tooltip(content="删除")
              i.icon-act.el-icon-delete(@click="deleteEmployee($event, scope.row, scope.$index)")
      el-pagination.ee-pagination(
        v-show="staffListTotal > 20"
        layout="prev, pager, next",
        :small="true"
        @current-change="changeEmployeePage",
        :current-page.sync="currentPage",
        :page-size="20",
        :total="staffListTotal")
  .limit-wrap
    el-tabs.lt-tabs(v-model="tabActName")
      el-tab-pane(v-for="(pane, index) in paneList", :label="pane.value", :name="pane.name", :key="index", :disabled="pane.name=='data'")
    .lt-func.c-lt-block(v-show="tabActName=='func'")
      RoleFunc(:editData="editFuncData", @save="saveLimits")
    //- .lt-route.c-lt-block(v-show="tabActName=='route'")
    .lt-data.c-lt-block(v-show="tabActName=='data'")
  el-dialog.dialog-wrap(
    title="添加自定义角色",
    :visible.sync="showDialog")
    h3 自定义角色名称
    p
      el-input(v-model="customRoleName", placeholder="自定义输入")
    el-row
      el-col(:span="24", style="text-align: center; margin-bottom: 16px")
        el-button(type="primary", style="width: 80px;", plain, @click="showDialog=false") 取消
        el-button(type="primary", style="width: 80px; margin-left: 40px;", @click="saveCustomRole") 添加
  el-dialog.dialog-wrap(
    title="添加角色员工",
    :visible.sync="showEmpDialog")
    h3
      span 添加以下员工为
      span(v-text="highLightRoleName", style="margin-left: 4px; color: #409EFF")
    p
      el-select(v-model="custemEmployees" multiple placeholder="请选择")
        el-option(v-for="item in roleStaffSelect", :key="item.value", :label="item.name", :value="item.value")
    el-row
      el-col(:span="24", style="text-align: center; margin-bottom: 16px")
         el-button(type="primary", style="width: 80px;", plain, @click="showEmpDialog=false") 取消
         el-button(type="primary", style="width: 80px; margin-left: 40px;", @click="saveRoleEmployee") 添加
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import ManApi from '@/api/manage';
import validate from '@/utils/validate';
import RoleFunc from '@/components/manage/role/RoleFunc';

const { isEmpty } = validate;

export default {
  name: 'manrole',
  data() {
    return {
      // 角色员工
      roleList: [],
      loadingRoles: true,
      employeeId: '',
      staffList: [],
      staffListTotal: 1,
      loadingStaffs: true,
      currentPage: 1,
      // 当前高亮角色ID
      highLightRoleId: null,
      highLightRoleName: '',
      // 权限Tab分组
      paneList: [
        { value: '功能权限', name: 'func' },
        // { value: '路由权限', name: 'route' },
        { value: '数据权限', name: 'data' },
      ],
      tabActName: 'func',
      editFuncData: [],
      // 弹层
      showDialog: false,
      customRoleName: '',
      showEmpDialog: false,
      roleStaffSelect: [],
      custemEmployees: []
    };
  },
  components: {
    RoleFunc
  },
  computed: {
    ...mapGetters(['empSelect'])
  },
  methods: {
    // 新增角色
    saveCustomRole () {
      if (isEmpty(this.customRoleName)) {
        this.$message.error('自定义角色名称不能为空');
        return false;
      }
      ManApi.saveCustomRole({ roleName: this.customRoleName }).then((result) => {
        if (!result.status) {
          this.roleList.push({
            id: result.obj.id,
            roleName: this.customRoleName,
            system: ''
          });
          this.$message.success('添加成功');
          this.customRoleName = '';
          this.showDialog = false;
        } else {
          this.$message.success(`添加失败：${result.comment}`);
        }
      });
    },
    // 新增角色下员工
    saveRoleEmployee () {
      if (!this.custemEmployees.length) {
        this.$message.error('请为该角色选择员工');
        return false;
      }
      const params = {
        roleId: this.highLightRoleId,
        empIds: this.custemEmployees
      };
      ManApi.saveRoleEmployee(params).then((result) => {
        if (!result.status) {
          this.$message.success('添加成功');
          result.obj.forEach((employee) => {
            this.staffList.unshift(employee);
            this.staffListTotal += result.obj.length;
          });
          this.showEmpDialog = false;
        } else {
          this.$message.error(`添加失败：${result.comment}`);
        }
      });
    },
    // 搜索角色下员工
    searchRoleEmployee () {
      this.loadingStaffs = true;
      ManApi.getStaffList({
        employeeId: this.employeeId,
        roleId: this.highLightRoleId
      }).then((result) => {
        if (!result.status) {
          this.staffList = result.obj.records;
          this.staffListTotal = result.obj.totalNum;
          this.currentPage = 1;
        } else {
          this.staffList = [];
          this.staffListTotal = 1;
          this.$message.error('此角色下没有员工');
        }
        this.loadingStaffs = false;
      }).catch((error) => {
        this.loadingStaffs = false;
        console.log(JSON.stringify(error));
      });
    },
    addStaffForRole () {
      this.showEmpDialog = true;
      this.custemEmployees = [];
      ComApi.getUnRoleEmployees({ roleId: this.highLightRoleId }).then((result) => {
        if (!result.status) {
          this.roleStaffSelect = result.obj;
        }
      });
    },
    changeEmployeePage (currentPage) {
      if (currentPage > 1) {
        this.loadingStaffs = true;
        ManApi.getStaffList({ pageNum: currentPage }).then((result) => {
          if (!result.status) {
            this.staffList = result.obj.records;
            this.staffListTotal = result.obj.totalNum;
            this.currentPage = currentPage;
          } else {
            this.$message.error(result.comment);
          }
          this.loadingStaffs = false;
        }).catch((error) => {
          this.loadingStaffs = false;
          console.log(JSON.stringify(error));
        });
      }
    },
    // 选择角色
    tableRowClassName ({ row }) {
      if (this.highLightRoleId === row.id) {
        return 'focus-row';
      }

      return '';
    },
    clickRoleRow (role) {
      this.highLightRoleId = role.id;
      this.highLightRoleName = role.roleName;
      this.loadingStaffs = true;
      // 取得相应角色下的员工
      ManApi.getStaffList({ roleId: role.id }).then((result) => {
        if (!result.status) {
          this.staffList = result.obj.records;
          this.staffListTotal = result.obj.totalNum;
          this.currentPage = 1;
        } else {
          this.staffList = [];
          this.staffListTotal = 1;
          this.$message.error('此角色下没有员工');
        }
        this.loadingStaffs = false;
      }).catch((error) => {
        this.loadingStaffs = false;
        console.log(JSON.stringify(error));
      });
      // 取得角色下的具体权限
      this.showLimitLoading();
      ManApi.getRoleLimits({ id: role.id }).then((rolResult) => {
        if (!rolResult.status) {
          this.editFuncData = rolResult.obj;
        }
        this.hideLimitLoading();
      }).catch((error) => {
        this.hideLimitLoading();
        console.log(JSON.stringify(error));
      });
    },
    // 删除自定义角色
    deleteRole (e, role, index) {
      e.stopPropagation();
      // 取得相应角色下的员工
      ManApi.getStaffList({ roleId: role.id }).then((result) => {
        if (!result.status) {
          this.$message.error('请先删除该角色下所有员工');
        } else {
          this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteRoleRow(role, index);
          }).catch(() => {
            this.$message.info('已取消删除');
          });
        }
      });
    },
    deleteRoleRow (role, index) {
      ManApi.deleteRole({ id: role.id }).then((result) => {
        if (!result.status) {
          this.$message.success('删除成功');
          // 切换焦点
          if (this.highLightRoleId === role.id) {
            let item = this.roleList[index + 1];
            if (!item) {
              item = this.roleList[0];
            }
            this.clickRoleRow(item);
          }
          this.roleList.splice(index, 1);
        } else {
          this.$message.error(result.comment);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    // 删除角色下员工
    deleteEmployee (e, emp, index) {
      e.stopPropagation();
      this.deleteEmployeeRow(emp, index);
    },
    deleteEmployeeRow (emp, index) {
      this.$confirm('此操作将删除该角色下员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loadingStaffs = true;
        const params = {
          roleId: this.highLightRoleId,
          empId: emp.employeeId
        };
        ManApi.deleteRoleEmployee(params).then((result) => {
          this.loadingStaffs = false;
          if (!result.status) {
            this.staffList.splice(index, 1);
            this.staffListTotal = this.staffListTotal - 1;
            this.$message.success('删除成功');
          } else {
            this.$message.error(`删除失败：${result.comment}`);
          }
        }).catch((error) => {
          console.log(JSON.stringify(error));
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 保存角色功能权限
    saveLimits (checkedKeys) {
      this.showLimitLoading();
      ManApi.saveRoleLimits({
        roleId: this.highLightRoleId,
        authIds: checkedKeys
      }).then((result) => {
        if (!result.status) {
          this.$message.success('保存成功');
          this.limitLoading.close();
        } else {
          this.$message.error(`保存失败：${result.comment}`);
        }
      }).catch((error) => {
        console.log(JSON.stringify(error));
      });
    },
    // 权限loading显隐
    showLimitLoading () {
      this.limitLoading = this.$loading({
        target: '.lt-func',
        body: true,
        fullscreen: false
      });
    },
    hideLimitLoading () {
      this.limitLoading.close();
    },
  },
  beforeRouteEnter (to, from, next) {
    next();
  },
  created () {
  },
  mounted () {
    this.showLimitLoading();
    ManApi.getRoleList().then((result) => {
      if (!result.status) {
        // 取得当前高亮角色
        const roleList = result.obj;
        this.roleList = roleList;
        if (roleList.length) {
          this.highLightRoleId = roleList[0].id;
          this.highLightRoleName = roleList[0].roleName;
        }
        // 取得高亮角色下的员工
        ManApi.getStaffList({ roleId: this.highLightRoleId }).then((staResult) => {
          if (!staResult.status) {
            this.staffList = staResult.obj.records;
            this.staffListTotal = result.obj.totalNum;
          } else {
            this.$message.error('此角色下没有员工');
          }
          this.loadingStaffs = false;
        }).catch((error) => {
          this.loadingStaffs = false;
          console.log(JSON.stringify(error));
        });
        // 取得高亮角色下的权限
        ManApi.getRoleLimits({ id: this.highLightRoleId }).then((rolResult) => {
          if (!rolResult.status) {
            const roleLimits = rolResult.obj;
            this.editFuncData = roleLimits;
          }
          this.hideLimitLoading();
        }).catch((error) => {
          this.hideLimitLoading();
          console.log(JSON.stringify(error));
        });
      }
      this.loadingRoles = false;
    }).catch((error) => {
      this.loadingRoles = false;
      this.loadingStaffs = false;
      this.limitLoading.close();
      console.log(JSON.stringify(error));
    });
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
$ROLEWIDTH: 320px
$PADDINGWIDTH: 16px
$TABHEIGHT: 40px
.cp-manage-role
  .role-staff-wrap
    position: absolute
    top: $PADDINGWIDTH
    bottom: $PADDINGWIDTH
    left: $PADDINGWIDTH
    width: $ROLEWIDTH
    // border: 1px solid gray
    overflow-x: hidden
    overflow-y: auto
    .role-wrap
      .re-pagination
        margin-top: 4px
    .staff-wrap
      margin-top: 16px
      .ee-pagination
        margin-top: 4px
    .wrap-title
      position: relative
      font-size: 14px
      padding-left: 8px
      @include hlfc(32px, 14px, #999, 500)
      .title-add
        display: inline-block
        position: absolute
        top: 0
        right: 16px
        color: #409EFF
      .title-search
        width: 160px
        margin-left: 16px
  .limit-wrap
    position: absolute
    top: $PADDINGWIDTH
    bottom: $PADDINGWIDTH
    left: $ROLEWIDTH + 32px
    right: $PADDINGWIDTH
    // border: 1px solid gray
    background: white
    overflow-x: hidden
    overflow-y: auto
    .lt-tabs
      position: relative
      height: $TABHEIGHT
      background: white
      padding-left: 20px
      .el-tabs__item:focus.is-active.is-focus:not(:active)
        box-shadow: none
      .el-tabs__nav-wrap::after
        background-color: white
    .c-lt-block
      position: absolute
      top: $TABHEIGHT
      bottom: 0
      left: 0
      right: 0
      overflow: hidden
    .lt-func
      padding: 16px
    .lt-data
      background: green
  .dialog-wrap
    h3
      margin-bottom: 8px
      font-weight: 500
    p
      width: 360px
      margin-bottom: 32px
    .el-select
      width: 100%
  table
    &::before
      display: none
    .icon-act
      font-size: 16px
      margin-left: 3px
      margin-right: 3px
  .el-table .focus-row td
    background: lightgoldenrodyellow
</style>
